import React, {Component} from 'react';
import Prompt from 'react-router-dom/Prompt';
import withStyles from 'material-ui/styles/withStyles';
import withRouter from 'react-router-dom/withRouter';

import Slide from 'material-ui/transitions/Slide';
import MuiButton from 'material-ui/Button/Button';
import Button from './Button';
import Typography from 'material-ui/Typography/Typography';
import List from 'material-ui/List/List';
import ListItem from 'material-ui/List/ListItem';
import ListItemText from 'material-ui/List/ListItemText';
import ListItemSecondaryAction from 'material-ui/List/ListItemSecondaryAction';
import Checkbox from 'material-ui/Checkbox/Checkbox';
import Grow from 'material-ui/transitions/Grow';
import IconButton from 'material-ui/IconButton/IconButton';

import KeyboardArrowLeft from 'material-ui-icons/KeyboardArrowLeft';
import KeyboardArrowRight from 'material-ui-icons/KeyboardArrowRight';

import medal_background from 'assets/medal_background.png';
import medal_genius from 'assets/medal_genius.png';
import medal_guardian from 'assets/medal_guardian.png';
import medal_noob from 'assets/medal_noob.png';

import green from 'material-ui/colors/green';
import red from 'material-ui/colors/red';

const SimpleQuestion = (
  {
    question: {
      id,
      content,
      answers,
      selectedId = false,
      correctId = false,
    },
    handler,
    classes: {
      root: rootClass,
      question: quesClass,
      answerCorrect,
      answerWrong
    } = {},
    texts,
    ...others
  }
) => (
  <div {...others} className={rootClass}>
    <Typography paragraph className={quesClass}>
      {content.split('\n').map(text => [text, <br key={`${text}-br`}/>])}
    </Typography>
    {answers.map(({id: answerId, content}, answerIndex) => (
      <ListItem
        key={`question:${id}-answer:${answerId}`}
        button={correctId === false}
        onClick={() => {
          selectedId === false && handler(id, answerId)
        }}
      >
        <ListItemText
          classes={{text: selectedId === answerId ? (selectedId === correctId ? answerCorrect : answerWrong) : undefined}}
          primary={`${String.fromCharCode(0x41 + answerIndex)}：${content}`}
          secondary={correctId === answerId && texts['correct-answer']}
        />
        <ListItemSecondaryAction>
          <Checkbox
            disabled={selectedId !== false}
            checked={selectedId === answerId}
            onClick={() => {
              selectedId === false && handler(id, answerId)
            }}
          />
        </ListItemSecondaryAction>
      </ListItem>
    ))}
  </div>
);

const style = ({spacing: {unit}}) => ({
  caption: {
    marginTop: unit,
    marginBottom: unit
  },
  slideContainer: {
    position: 'relative',
    marginTop: unit,
    flexGrow: 1
  },
  slider: {
    flexGrow: 1,
    position: 'absolute',
    top: 0,
    width: '100%'
  },
  finishedActions: {
    display: 'flex',
    justifyContent: 'space-around',
    margin: unit *2,
    marginTop: unit *4,
    '& button': {
      minWidth: 120
    }
  },
  questionContent: {
    fontSize: '1.15rem'
  },
  answerCorrect: {
    color: green[600]
  },
  answerWrong: {
    color: red[600]
  },
  '@keyframes rotate': {
    from: {
      transform: 'rotate(0)'
    },
    to: {
      transform: 'rotate(360deg)'
    }
  },
  medalBackground: {
    boxSizing: 'border-box',
    position: 'relative',
    marginLeft: 'auto',
    marginRight: 'auto',
    width: '75%',
    minWidth: 320,
    padding: '15%',
    '&:before': {
      content: '""',
      display: 'block',
      width: '100%',
      paddingTop: '100%',
      left: 0, top: 0,
      position: 'absolute',
      backgroundRepeat: 'no-repeat',
      backgroundSize: 'contain',
      backgroundPosition: 'center',
      backgroundImage: `url(${medal_background})`,
      animation: 'rotate 5s infinite linear',
    }
  },
  medal: {
    backgroundSize: 'contain',
    backgroundRepeat: 'no-repeat',
    backgroundPosition: 'center',
    width: '100%',
    position: 'relative',
    overflow: 'hidden',
    '&:before': {
      content: '""',
      display: 'block',
      marginTop: '100%',
    }
  },
  medalText: {
    position: 'absolute',
    color: '#fff',
    top: 0, left: 0,
    bottom: 0, right: 0,
    fontFamily: 'MFYueYuan',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    lineHeight: 1.125,
    marginTop: '-.5em',
    fontSize: 42,
    '& > *': {
      width: '2em'
    }
  },
  stepper: {
    boxSizing: 'border-box',
    width: '100%',
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between'
  },
  guideShare: {
    position: 'absolute',
    width: '100%',
    bottom: 0
  }
});


@withRouter
@withStyles(style)
class Question extends Component{
  state = {
    questions: [],
    currentIndex: 0,
    transitionState: 'in', // [in, next, previous]
    currentDirection: 'left',
    finished: false,
    showMedal: false,
    count_correct: 0
  };

  componentWillMount() {
    const {
      texts, classes
    } = this.props;

    const defaultProps = SimpleQuestion.defaultProps || {};

    SimpleQuestion.defaultProps = {
      ...defaultProps,
      classes: {
        ...defaultProps.classes,
        root: classes.slider,
        question: classes.questionContent,
        answerCorrect: classes.answerCorrect,
        answerWrong: classes.answerWrong
      },
      texts
    }
  }

  componentDidMount() {
    this.reset();
  }


  reset = () => {
    this.props.getQuestions(9).then(questions => {
      this.setState({
        questions,
        transitionState: 'in',
        currentDirection: 'left',
        currentIndex: 0,
        count_correct: 0,
        finished: false,
        showMedal: false
      })
    })
  }

  handleAnswer = (questionId, answerId) => {
    this.props.checkAnswer(questionId, answerId)
      .then(({isCorrect, correctAnswer}) => {
        const questions = this.state.questions.map(question => (
          question.id === questionId
            ? {...question, correctId: correctAnswer, selectedId: answerId}
            : question
        ));
        const count_correct = this.state.count_correct + Number(isCorrect);
        this.setState(
          {questions, count_correct},
          () => {
            setTimeout(this.nextQuestion, 1500) // 1.5秒切换下一题
          }
        )
      });
  }

  nextQuestion = () => {
    if (this.state.currentIndex +1 < this.state.questions.length) {
      this.setState({transitionState: 'next'})
    } else {
      this.setState({transitionState: 'next', finished: true})
    }
  }

  prevQuestion = () => {
    if (this.state.currentIndex > 0)
      this.setState({transitionState: 'previous'})
  }

  render() {
    const {
      match,
      location,
      history,
      classes,
      texts
    } = this.props;

    const {
      questions,
      currentIndex,
      transitionState,
      currentDirection,
      count_correct,
      finished,
      showMedal
    } = this.state;

    const currQuestion = questions[currentIndex];
    const nextQuestion = currentIndex < questions.length -1 && questions[currentIndex +1];
    const prevQuestion = currentIndex > 0 && questions[currentIndex -1];

    const resultLevel = Math.max(Math.round(count_correct/questions.length*3), 1);

    return ([
      <Prompt
        key="question-prompt"
        when={finished === false && currentIndex > 0}
        message={texts['confirm-exit']}
      />,

      <div className={classes.stepper} key="question-stepper">
        <IconButton
          disabled={!prevQuestion || finished}
          onClick={() => {this.setState({transitionState: 'previous'})}}
        >
          <KeyboardArrowLeft/>
        </IconButton>

        <Typography
          type="caption"
          className={classes.caption}
        >
          {finished
            ? texts['result-tpl'].replace('{NUM}', count_correct)
            : texts['caption-tpl'].replace('{NUM}', `${currentIndex+1}/${questions.length}`)}
        </Typography>

        <IconButton
          disabled={!nextQuestion || finished}
          onClick={() => {this.setState({transitionState: 'next'})}}
        >
          <KeyboardArrowRight/>
        </IconButton>
      </div>,

      <div key="question-body" className={classes.slideContainer}>
        {finished &&
        <Typography type="caption" align="center" className={classes.guideShare}>
          动动你的手指，分享给好友，让更多人获得禁毒知识
        </Typography>}

        {currQuestion &&
        <Slide
          key={`question:${currQuestion.id}`}
          in={transitionState === 'in'}
          onEntered={() => this.setState({currentDirection: 'right'})}
          direction={currentDirection}
        >
          <SimpleQuestion
            question={currQuestion}
            handler={this.handleAnswer}
          />
        </Slide>}

        {prevQuestion &&
        <Slide
          key={`question:${prevQuestion.id}`}
          in={transitionState === 'previous'}
          direction="right"
          onEnter={() => this.setState({currentDirection: 'left'})}
          onEntered={() => this.setState({currentIndex: currentIndex -1, transitionState: 'in'})}
        >
          <SimpleQuestion
            question={prevQuestion}
            handler={this.handleAnswer}
          />
        </Slide>}

        {nextQuestion &&
        <Slide
          key={`question:${nextQuestion.id}`}
          in={transitionState === 'next'}
          direction="left"
          onEnter={() => this.setState({currentDirection: 'right'})}
          onEntered={() => this.setState({currentIndex: currentIndex +1, transitionState: 'in'})}
        >
          <SimpleQuestion
            question={nextQuestion}
            handler={this.handleAnswer}
          />
        </Slide>}

        <Slide
          in={finished}
          direction="left"
          onEntered={() => this.setState({currentIndex: -1, transitionState: 'in', showMedal: true})}
        >
          <div className={classes.slider}>
            <Grow in={showMedal} duration={500}>
              <div className={classes.medalBackground}>
                <div style={{backgroundImage: `url(${{
                  1: medal_noob,
                  2: medal_guardian,
                  3: medal_genius
                }[resultLevel]})`}} className={classes.medal}>
                  <div className={classes.medalText}>
                    <div>
                      {{
                        1: '禁毒小白',
                        2: '禁毒达人',
                        3: '禁毒使者'
                      }[resultLevel]}
                    </div>
                  </div>
                </div>
              </div>
            </Grow>

            <div className={classes.finishedActions}>
              <Button
                raised
                onClick={() => {history.goBack()}}
              >
                {texts['action-exit']}
              </Button>
              <Button
                raised
                onClick={this.reset}
              >
                {texts['action-reset']}
              </Button>
            </div>

          </div>
        </Slide>
      </div>
    ])
  }
}

export default Question;
